package com.drinks.yiniang.ui.activity.search;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.search.SearchGoodsAdapter;
import com.drinks.yiniang.common.recycler.decoration.SearchGoodsItemDecoration;
import com.drinks.yiniang.common.recycler.decoration.ShoppingCartItemDecoration;
import com.drinks.yiniang.entity.goods.GoodsJson;
import com.drinks.yiniang.entity.goods.RecommendGoodsJson;
import com.drinks.yiniang.entity.goods.SearchGoodsJson;
import com.drinks.yiniang.io.api.GoodsApiIO;
import com.drinks.yiniang.io.api.ShoppingCartApiIO;
import com.drinks.yiniang.ui.activity.MainActivity;
import com.drinks.yiniang.ui.activity.goods.GoodsDetailsActivity;
import com.drinks.yiniang.ui.widget.nav.NavigationSearchBarLayout;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.drinks.yiniang.utils.RecyclerUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.entity.BaseJson;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.utils.ColorUtils;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

import static com.drinks.yiniang.entity.goods.SearchGoodsJson.ITEM_TYPE_SEARCH_GOODS_LIST;
import static com.drinks.yiniang.entity.goods.SearchGoodsJson.ITEM_TYPE_SEARCH_GOODS_TITLE;

/**
 * 搜索商品
 *
 * @author han
 * A simple {@link Fragment} subclass.
 */
public class SearchGoodsActivity extends BaseTranBarActivity implements TextView.OnEditorActionListener,
        BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.RequestLoadMoreListener {
    //nav
    private EditText et_search_goods_content;
    //取消
    private TextView tv_search_goods_cancel;
    //搜索提示语
    private TextView tv_search_goods_tips;
    private BaseRecyclerView rcv_search_goods;
    //header view
    //搜索为空view
    private LinearLayout ll_search_goods_empty;

    private SearchGoodsAdapter mSearchGoodsAdapter;

    //关键词
    private String mKeywords;
    //指定分类
    private String mCategoryId;

    private int mPages;

    @Override
    protected void initView() {
        et_search_goods_content = findViewById(R.id.et_search_goods_content);

        tv_search_goods_cancel = findViewById(R.id.tv_search_goods_cancel);
        tv_search_goods_tips = findViewById(R.id.tv_search_goods_tips);

        rcv_search_goods = findViewById(R.id.rcv_search_goods);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;

        mCategoryId = getIntent() != null ? getIntent().getStringExtra(Constants.KeyCategoryId) : null;

        initAdapter();
    }

    private void initAdapter() {
        mSearchGoodsAdapter = new SearchGoodsAdapter(mContext, new ArrayList<SearchGoodsJson.SearchGoodsList>());
        mSearchGoodsAdapter.addHeaderView(getHeaderView());
        mSearchGoodsAdapter.setHeaderAndEmpty(true);
        mSearchGoodsAdapter.setCenterEmpty(getLayoutInflater(), rcv_search_goods);
        mSearchGoodsAdapter.bindToRecyclerView(rcv_search_goods);

        rcv_search_goods.addItemDecoration(SearchGoodsItemDecoration.getItemDPDecoration(10));
        rcv_search_goods.setLayoutManager(RecyclerUtils.getSearchGoodsGridLayout(mContext, mSearchGoodsAdapter.getData()));
    }

    //获取header
    private View getHeaderView() {
        View mHeaderView = getLayoutInflater().inflate(R.layout.header_search_goods_empty, (ViewGroup) rcv_search_goods.getParent(), false);

        ll_search_goods_empty = mHeaderView.findViewById(R.id.ll_search_goods_empty);

        return mHeaderView;
    }

    @Override
    protected void initListener() {
        et_search_goods_content.setOnEditorActionListener(this);
        tv_search_goods_cancel.setOnClickListener(this);
        mSearchGoodsAdapter.setOnItemClickListener(this);
        mSearchGoodsAdapter.setOnItemChildClickListener(this);
        mSearchGoodsAdapter.setOnLoadMoreListener(this, rcv_search_goods);
    }

    @Override
    public void widgetClick(View v) {
        if(v.getId() == R.id.tv_search_goods_cancel) {
            finish();
        }
    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_search_goods;
    }


    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            hideKeyboard(this.getCurrentFocus().getWindowToken());
            mKeywords = StringUtils.getEditTextString(et_search_goods_content.getText());
            //TODO Search
            doSearchGoods();
        }
        return false;
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        SearchGoodsJson.SearchGoodsList data = mSearchGoodsAdapter.getItem(position);

        if(data == null) {
            return;
        }

        switch (adapter.getItemViewType(position + adapter.getHeaderLayoutCount())) {
            case ITEM_TYPE_SEARCH_GOODS_LIST:
                Intent intent = new Intent(mContext, GoodsDetailsActivity.class);
                intent.putExtra(Constants.KeyGoodsId, data.getId());
                startActivity(intent);
                break;
                default:
                    break;
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        SearchGoodsJson.SearchGoodsList data = mSearchGoodsAdapter.getItem(position);

        if(data == null) {
            return;
        }

        switch (adapter.getItemViewType(position + adapter.getHeaderLayoutCount())) {
            case ITEM_TYPE_SEARCH_GOODS_LIST:
                if(view.getId() == R.id.iv_home_goods_add_cart) {
                    addToCart(data.getId());
                }
                break;
            default:
                break;
        }
    }

    private void addToCart(String goodsId) {
        showLoadingDialog();

        ShoppingCartApiIO.getInstance().addToShopCart(goodsId, new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(BaseJson res) {
                ToastUtils.showShort(getString(R.string.text_add_success));
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    @Override
    public void onLoadMoreRequested() {
        GoodsApiIO.getInstance().doGoodsSearch(mPages, mCategoryId, mKeywords, new APIRequestCallback<SearchGoodsJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(SearchGoodsJson res) {
                mPages++;

                mSearchGoodsAdapter.addData(res.getData().getData());

                if (CommonUtils.isHasMoreData(res.getData().getData())) {
                    mSearchGoodsAdapter.loadMoreComplete();
                } else {
                    getRecommend();
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                mSearchGoodsAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    private void doSearchGoods() {
        if (StringUtils.isEmpty(mKeywords)) {
            return;
        }

        showLoadingDialog();

        mPages = 1;

        GoodsApiIO.getInstance().doGoodsSearch(mPages, mCategoryId, mKeywords, new APIRequestCallback<SearchGoodsJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(SearchGoodsJson res) {
                mPages++;

                mSearchGoodsAdapter.getData().clear();
                mSearchGoodsAdapter.addData(res.getData().getData());

                if(mSearchGoodsAdapter.getData().size() > 0) {
                    setSearchTipsText(mKeywords);
                } else {
                    setSearchTipsText(null);
                }

                if (CommonUtils.isHasMoreData(res.getData().getData())) {
                    mSearchGoodsAdapter.loadMoreComplete();
                } else {
                    getRecommend();
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                mSearchGoodsAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //获取推荐列表
    private void getRecommend() {
        GoodsApiIO.getInstance().getRecommendGoodsList(new APIRequestCallback<RecommendGoodsJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(RecommendGoodsJson res) {
                if (mSearchGoodsAdapter == null) {
                    return;
                }

                List<SearchGoodsJson.SearchGoodsList> ls = new ArrayList<>();
                SearchGoodsJson.SearchGoodsList data;

                if(res.getData().size() > 0) {
                    data = new SearchGoodsJson.SearchGoodsList();
                    data.setItemType(ITEM_TYPE_SEARCH_GOODS_TITLE);

                    ls.add(data);
                }

                for(GoodsJson.GoodsList goodsData : res.getData()) {
                    data = new SearchGoodsJson.SearchGoodsList();
                    data.setItemType(ITEM_TYPE_SEARCH_GOODS_LIST);
                    data.setId(goodsData.getId());
                    data.setApp_price(goodsData.getApp_price());
                    data.setName(goodsData.getName());
                    data.setCover_url(goodsData.getCover_url());
                    data.setEn_name(goodsData.getEn_name());
                    data.setRecommend_reason(goodsData.getRecommend_reason());
                    data.setIs_show_contrast(goodsData.getIs_show_contrast());
                    data.setActivity(goodsData.getActivity());
                    data.setActivity_price(goodsData.getActivity_price());

                    ls.add(data);
                }

                mSearchGoodsAdapter.addData(ls);
                mSearchGoodsAdapter.loadMoreEnd();
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                mSearchGoodsAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void setSearchTipsText(String tips) {
        if (StringUtils.isEmpty(tips)) {
            tv_search_goods_tips.setText(tips);
            tv_search_goods_tips.setVisibility(View.GONE);

            ll_search_goods_empty.setVisibility(View.VISIBLE);
        } else {
            ll_search_goods_empty.setVisibility(View.GONE);

            SpannableStringBuilder builder = new SpannableStringBuilder("您搜索的内容“");
            int start = builder.length();
            builder.append(tips);
            builder.append("”");
            builder.setSpan(new ForegroundColorSpan(ColorUtils.getColorById(mContext, R.color.color_4974db)), start, builder.length() - 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

            tv_search_goods_tips.setVisibility(View.VISIBLE);
            tv_search_goods_tips.setText(builder);
        }
    }
}
